from django.shortcuts import render

# Create your views here.
from search.models import *
import os
from elasticsearch import Elasticsearch
from django.views.decorators.csrf import csrf_exempt
from django.views import View
import json
from django.http import JsonResponse, HttpResponse
from datetime import datetime
class SearchByTitle(View):
    @csrf_exempt
    def post(self, request):
        res={}
        reslist=[]
        kwargs: dict = json.loads(request.body)
        identTitle=kwargs["keyword"]

        print(identTitle)
        bodyText = {
            "query": {
                "match": {
                    "title": identTitle
                }
            }
        }
        es = Elasticsearch(['127.0.0.1:9200'])
        rres = es.search(index='sciencesaki', size=500, body=bodyText)
        time=rres['hits']['total']['value']
        print(time)
        r=rres['hits']['hits']
        print(r[0]['_source']['text'])
        for i in range(len(r)):
            reslist.append(r[i]['_source']['text'].split("\n"))
        res['time']=time
        res['result']=reslist

        #reslist = (str(rres['hits']['hits'][10]['_source']['text']).split("\n"))
        return JsonResponse(json.dumps(res), safe=False)

class SearchByAuthor(View):
    @csrf_exempt
    def post(self, request):
        res=[]
        kwargs: dict = json.loads(request.body)
        identAuthors=kwargs["keyword"]
        bodyText = {
            "query": {
                "match": {
                    "authors": identAuthors
                }
            }
        }
        es = Elasticsearch(['127.0.0.1:9200'])
        rres = es.search(index='sciencesaki', size=20, body=bodyText)
        print(rres)
        r=rres['hits']['hits']
        print(r)
        for i in range(len(r)):
            res.append(r[i]['_source']['text'])
        print(res)
        return JsonResponse(json.dumps(res), safe=False)



class SortByRef(View):
    @csrf_exempt
    def post(self, request):
        res = {}
        reslist = []
        kwargs: dict = json.loads(request.body)
        ident=kwargs["keyword"]
        bodyText = {
            "query": {
                "match": {
                    "authors": ident
                },
                "sort": {
                    "ref_wf": {  # 根据引用量字段降序排序
                        "order": "desc"  # asc升序，desc降序
                    }
                }
            }
        }
        es = Elasticsearch(['127.0.0.1:9200'])
        rres = es.search(index='sciencesaki', size=20, body=bodyText)
        time = rres['hits']['total']['value']
        print(time)
        r = rres['hits']['hits']
        # print(r)
        for i in range(len(r)):
            reslist.append(r[i]['_source']['text'].split("\n"))
        res['time'] = time
        res['result'] = reslist



        # reslist = (str(rres['hits']['hits'][10]['_source']['text']).split("\n"))
        return JsonResponse(json.dumps(res), safe=False)

class Select(View):
    @csrf_exempt
    def post(self, request):
        res = {}
        reslist = []
        kwargs: dict = json.loads(request.body)
        identTitle = kwargs["keyword"]
        arr=kwargs["shaixuan"]
        print(arr[0])
        yearlist=arr[0].split("-")
        print(yearlist)

        bodyText = {
            "query": {
                "bool": {
                    "must": [{
                        "match": {
                            "title": identTitle
                        }
                    },{
                        "range": {
                            "publish_year":{
                                "gte":yearlist[0],       # >=
                                "lte":yearlist[1]        # <=
                            }
                        }
                    }
                ]
  }
            }
        }
        es = Elasticsearch(['127.0.0.1:9200'])
        rres = es.search(index='sciencesaki', size=500, body=bodyText)
        time = rres['hits']['total']['value']
        print(time)
        r = rres['hits']['hits']
        # print(r)
        for i in range(len(r)):
            reslist.append(r[i]['_source']['text'].split("\n"))
        res['time'] = time
        res['result'] = reslist


        # reslist = (str(rres['hits']['hits'][10]['_source']['text']).split("\n"))
        return JsonResponse(json.dumps(res), safe=False)


class SearchByTitle(View):
    @csrf_exempt
    def post(self, request):
        kwargs: dict = json.loads(request.body)
        id=kwargs['lid']
        paper=Papers.object.get(id=id)
        res = {}
        res['collectFlag'] = 1
        res['aid'] = id
        res['headline']=paper.title
        res['reading']=1
        res['auther']=paper.author
        res['abstract']=paper.
        return JsonResponse(json.dumps(res), safe=False)